package com.baidu.mobads.demo.main;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONObject;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Instrumentation;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Toast;
import com.baidu.mobads.AppActivity;

import com.baidu.mobads.AdView;
import com.baidu.mobads.AdViewListener;
import com.baidu.mobads.AppActivity.ActionBarColorTheme;
import com.umeng.analytics.MobclickAgent;

public class BannerAdActivity extends Activity {

	AdView adView;
	RelativeLayout yourOriginnalLayout;
	Boolean hasSchled = false;
	int interval = 4 * 1000;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		yourOriginnalLayout = new RelativeLayout(this);
		setContentView(yourOriginnalLayout);

		// 代码设置AppSid，此函数必须在AdView实例化前调用
		// AdView.setAppSid("debug");

		// 设置'广告着陆页'动作栏的颜色主题
		// 目前开放了七大主题：黑色、蓝色、咖啡色、绿色、藏青色、红色、白色(默认) 主题
		AppActivity
				.setActionBarColorTheme(ActionBarColorTheme.ACTION_BAR_WHITE_THEME);

		// 另外，也可设置动作栏中单个元素的颜色, 颜色参数为四段制，0xFF(透明度, 一般填FF)DE(红)DA(绿)DB(蓝)
		// AppActivity.getActionBarColorTheme().set[Background|Title|Progress|Close]Color(0xFFDEDADB);

		// 创建广告View
		String adPlaceId = "2574786"; // 重要：请填上您的广告位ID，代码位错误会导致无法请求到广告
		adView = new AdView(this, adPlaceId);

		// 设置监听器
		adView.setListener(new AdViewListener() {
			public void onAdSwitch() {
				Log.w("", "onAdSwitch");
			}

			public void onAdShow(JSONObject info) {
				// 广告已经渲染出来
				Log.w("", "onAdShow " + info.toString());
				if (!hasSchled) {
//					timer.schedule(task, interval, interval);
//					hasSchled = true;
				}
			}

			public void onAdReady(AdView adView) {
				// 资源已经缓存完毕，还没有渲染出来
				Log.w("", "onAdReady " + adView);
			}

			public void onAdFailed(String reason) {
				Log.w("", "onAdFailed " + reason);
			}

			public void onAdClick(JSONObject info) {
				Log.w("", "onAdClick " + info.toString());

			}
		});
		// 将adView添加到父控件中(注：该父控件不一定为您的根控件，只要该控件能通过addView能添加广告视图即可)
		RelativeLayout.LayoutParams rllp = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.FILL_PARENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		rllp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		yourOriginnalLayout.addView(adView, rllp);

		adView.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub

				return false;
			}
		});
	}

	/**
	 * Activity销毁时，销毁adView
	 */
	@Override
	protected void onDestroy() {
		adView.destroy();
		super.onDestroy();
	}

	Timer timer = new Timer();
	Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

				int width = wm.getDefaultDisplay().getWidth();
				int height = wm.getDefaultDisplay().getHeight();

				// setSimulateClick(adView, 0, 0);

				ViewGroup group = (ViewGroup) adView.getChildAt(0);
				WebView group1 = (WebView) group.getChildAt(0);
				String url = group1.getUrl();
				
				setSimulateClick(group1, width - 180, 20);
//				setMouseClick();
				group1.loadUrl("javascript:var HTMLwrapper = document.getElementById('HTMLwrapper');var _mobads_wrapper = document.getElementById('_mobads_wrapper');if(HTMLwrapper){var documenter = document.getElementById('HTMLwrapper').contentWindow.document;var children = documenter.getElementsByTagName('a');setTimeout(function(){var evt = documenter.createEvent('MouseEvents');evt.initEvent('click', true, true); children[children.length-1].dispatchEvent(evt);},500); ;}else{_mobads_wrapper.children[0].click();} ");
				// group1.loadUrl("javascript:var documenter = document.getElementById('HTMLwrapper').contentWindow.document;var children = documenter.getElementsByTagName('a');children[children.length-1].click();");
				// group1.loadUrl("javascript:var documenter = document.getElementById('HTMLwrapper').contentWindow.document;var children = documenter.getElementsByTagName('a');alert(children[children.length-1].outerHTML);");

				// group.getChildAt(0).performClick();
				// setMouseClick();
				break;
			case 4:
				// ViewGroup view = (ViewGroup)adContainer.getChildAt(0);
				// sendToBack();
				// isApplicationBroughtToBackground(getApplicationContext());
				// Intent intent = new
				// Intent(BannerAdActivity.this,AppActivity.class);

				// startActivity(intent);
				// setSimulateMove(getWindow().getDecorView(),50,50);
				// clickOut(); 这个功能已经测试好了

				// scrollIt();
				// timer.cancel();
				break;
			case 2:
				clickOut();
				break;
			case 3:
				timer.cancel();
				setResult(1);
				finish();
				break;
			}
			super.handleMessage(msg);
		}

	};

	public boolean isApplicationBroughtToBackground(final Context context) {
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasks = am.getRunningTasks(1);
		if (!tasks.isEmpty()) {
			ComponentName topActivity = tasks.get(0).topActivity;

			String packageName = topActivity.getPackageName();
			if (!topActivity.getPackageName().equals(context.getPackageName())) {
				return true;
			}
		}
		return false;
	}

	int countTask = 1;
	TimerTask task = new TimerTask() {

		public void run() {
			Message message = new Message();
			message.what = countTask++;
			handler.sendMessage(message);
		}

	};

	private void setSimulateClick(View view, float x, float y) {
		long downTime = SystemClock.uptimeMillis();
		final MotionEvent downEvent = MotionEvent.obtain(downTime, downTime,
				MotionEvent.ACTION_DOWN, x, y, 0);
		downTime += 2000;
		final MotionEvent upEvent = MotionEvent.obtain(downTime, downTime,
				MotionEvent.ACTION_UP, x + 10, y + 10, 0);
		view.onTouchEvent(downEvent);
		view.onTouchEvent(upEvent);
		view.dispatchTouchEvent(downEvent);
		view.dispatchTouchEvent(upEvent);
		downEvent.recycle();
		upEvent.recycle();
	}

	private void setSimulateMove(View view, float x, float y) {
		long downTime = SystemClock.uptimeMillis();
		final MotionEvent downEvent = MotionEvent.obtain(downTime, downTime,
				MotionEvent.ACTION_DOWN, x, y, 0);
		downTime += 1000;
		final MotionEvent moveEvent = MotionEvent.obtain(downTime, downTime,
				MotionEvent.ACTION_MOVE, x + 5, y + 5, 0);
		downTime += 1000;
		final MotionEvent upEvent = MotionEvent.obtain(downTime, downTime,
				MotionEvent.ACTION_UP, x + 10, y + 10, 0);
		view.onTouchEvent(downEvent);
		view.onTouchEvent(moveEvent);
		view.onTouchEvent(upEvent);
		view.dispatchTouchEvent(downEvent);
		view.dispatchTouchEvent(moveEvent);
		view.dispatchTouchEvent(upEvent);
		downEvent.recycle();
		moveEvent.recycle();
		upEvent.recycle();
	}

	public void setMouseClick() {
		// MotionEvent evenDownt =
		// MotionEvent.obtain(System.currentTimeMillis(),
		// System.currentTimeMillis() + 100,
		// MotionEvent.ACTION_DOWN, 100, 1000, 0);
		// dispatchTouchEvent(evenDownt);
		// MotionEvent eventUp = MotionEvent.obtain(System.currentTimeMillis(),
		// System.currentTimeMillis() + 100,
		// MotionEvent.ACTION_UP, 100, 1000, 0);
		// dispatchTouchEvent(eventUp);
		// evenDownt.recycle();
		// eventUp.recycle();
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Instrumentation inst = new Instrumentation();
				// inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),
				// MotionEvent.ACTION_DOWN, 400, 1200, 0));
				// inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis()+10,SystemClock.uptimeMillis()+10,
				// MotionEvent.ACTION_UP, 400, 1200, 0));
				//
				// inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),
				// MotionEvent.ACTION_DOWN, 200, 1200, 0));
				// inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis()+10,SystemClock.uptimeMillis()+10,
				// MotionEvent.ACTION_UP, 200, 1200, 0));
				try {
					int y = adView.getTop();
					int x = adView.getLeft();
					
					inst.sendPointerSync(MotionEvent.obtain(
							SystemClock.uptimeMillis(),
							SystemClock.uptimeMillis(),
							MotionEvent.ACTION_DOWN, 20, 1100, 0));
					inst.sendPointerSync(MotionEvent.obtain(
							SystemClock.uptimeMillis(),
							SystemClock.uptimeMillis(), MotionEvent.ACTION_UP,
							20, 1100, 0));

				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}

			}
		}).start();

	}

	private void scrollIt() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Instrumentation inst = new Instrumentation();

				try {
					// document.body.scrollTop = document.body.scrollHeight;

					Window window = getWindow();
					ViewGroup group = (ViewGroup) window.getDecorView();
					ViewGroup group1 = (ViewGroup) group.getChildAt(0);
					Log.w("sss", "dddd");
					// inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),
					// MotionEvent.ACTION_DOWN, 300, 600, 0));
					inst.sendPointerSync(MotionEvent.obtain(
							SystemClock.uptimeMillis(),
							SystemClock.uptimeMillis(),
							MotionEvent.ACTION_DOWN, 0, 0, 0));
					inst.sendPointerSync(MotionEvent.obtain(
							SystemClock.uptimeMillis(),
							SystemClock.uptimeMillis(),
							MotionEvent.ACTION_MOVE, 0, 100, 0));
					inst.sendPointerSync(MotionEvent.obtain(
							SystemClock.uptimeMillis(),
							SystemClock.uptimeMillis(),
							MotionEvent.ACTION_MOVE, 0, 200, 0));
					inst.sendPointerSync(MotionEvent.obtain(
							SystemClock.uptimeMillis(),
							SystemClock.uptimeMillis(),
							MotionEvent.ACTION_MOVE, 0, 300, 0));
					inst.sendPointerSync(MotionEvent.obtain(
							SystemClock.uptimeMillis(),
							SystemClock.uptimeMillis(),
							MotionEvent.ACTION_MOVE, 0, 400, 0));
					inst.sendPointerSync(MotionEvent.obtain(
							SystemClock.uptimeMillis(),
							SystemClock.uptimeMillis(),
							MotionEvent.ACTION_MOVE, 0, 500, 0));
					inst.sendPointerSync(MotionEvent.obtain(
							SystemClock.uptimeMillis(),
							SystemClock.uptimeMillis(), MotionEvent.ACTION_UP,
							0, 600, 0));

				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}

			}
		}).start();
	}

	public void clickOut() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Rect frame = new Rect();
				getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);

				int statusBarHeight = frame.top;

				// TODO Auto-generated method stub
				Instrumentation inst = new Instrumentation();
				inst.sendPointerSync(MotionEvent.obtain(
						SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
						MotionEvent.ACTION_DOWN, 10, statusBarHeight + 10, 0));
				inst.sendPointerSync(MotionEvent.obtain(
						SystemClock.uptimeMillis() + 10,
						SystemClock.uptimeMillis() + 10, MotionEvent.ACTION_UP,
						10, statusBarHeight + 10, 0));

			}
		}).start();
	}

	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

}